package com.hanlink.dsp.ca.ui.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;

import com.edge.pbxdsp.R;
import com.hanlink.dsp.ca.model.channel.LevelChannel;
import com.hanlink.dsp.ui.widget.AdvanceChannel;
import com.hanlink.dsp.ui.widget.AdvanceTimeDelay;
import com.hanlink.dsp.util.BLog;
import com.hanlink.dsp.util.Constants;
import com.hanlink.dsp.util.DataUtil;
import com.hanlink.dsp.util.ViewUtil;
import com.qztech.sdk.ui.fragment.ChannelFragment;
import com.qztech.utils.YzDebug;

import java.util.List;

//import butterknife.BindView;
//import butterknife.BindViews;
//import butterknife.OnClick;

import static com.hanlink.dsp.DspSettings.ADVANCE_SETTINGS;
import static com.hanlink.dsp.util.Constants.DIENABLED_ALPHA;

public class AdvanceFragment extends ChannelFragment {

    private CheckBox cb1,cb2,cb3,cb4,cb5,cb6,cb7,cb8;
   // @BindViews({R.id.cbBtnCh1, R.id.cbBtnCh2, R.id.cbBtnCh3, R.id.cbBtnCh4, R.id.cbBtnCh5, R.id.cbBtnCh6, R.id.cbBtnCh7, R.id.cbBtnCh8})
    CheckBox[] cbxChannels;//Leve CH

    private RadioButton rb1,rb2,rb3,rb4,rb5,rb6,rbBtnCen,rbBtnSub;
    //@BindViews({R.id.rbBtnCh1, R.id.rbBtnCh2, R.id.rbBtnCh3, R.id.rbBtnCh4, R.id.rbBtnCh5, R.id.rbBtnCh6, R.id.rbBtnCen, R.id.rbBtnSub})
    RadioButton[] rbtnChannels;//Time-delay CH
    //@BindView(R.id.rgp_channels)
    RadioGroup rgpChannels;

    private AdvanceTimeDelay atd1,atd2,atd3,atd4,atd5,atd6,atd7,atd8;
   // @BindViews({R.id.atd_1, R.id.atd_2, R.id.atd_3, R.id.atd_4, R.id.atd_5, R.id.atd_6, R.id.atd_7, R.id.atd_8})
    AdvanceTimeDelay[] advanceTimeDelays;

    private AdvanceChannel eqc_1,eqc_2,eqc_3,eqc_4,eqc_5,eqc_6,eqc_7,eqc_8;
    //@BindViews({R.id.eqc_1, R.id.eqc_2, R.id.eqc_3, R.id.eqc_4, R.id.eqc_5, R.id.eqc_6, R.id.eqc_7, R.id.eqc_8})
    AdvanceChannel[] mEqChannel;


    private CheckBox link1,link2,link3,link4,link5,link6,link7,link8;
    //@BindViews({R.id.link1, R.id.link2, R.id.link3, R.id.link4, R.id.link5, R.id.link6, R.id.link7, R.id.link8})
    CheckBox[] mLinks;
    //@BindView(R.id.cbx_mute)
    CheckBox mCbxMute;
    //@BindView(R.id.seekBarTotal)
    SeekBar sbTotalVol;//总音量

    @Override
    public void setOnBottomBtnClickListener(View.OnClickListener bottomBtnClickListener) {
        super.setOnBottomBtnClickListener(bottomBtnClickListener);
    }

    //@BindView(R.id.txt_db_value)
    TextView txtTotalVol;
    //加减总音量
    //@BindView(R.id.ibtn_total_plus)
    ImageButton mBtnPlus;
    //@BindView(R.id.ibtn_total_sub)
    ImageButton mBtnSub;

    private long mLastChangedTs;
    @Override
    protected int getResourceId() {
        return R.layout.fragment_advance;
    }
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        cb1 = findViewById(R.id.cbBtnCh1);
        cb2 = findViewById(R.id.cbBtnCh2);
        cb3 = findViewById(R.id.cbBtnCh3);
        cb4 = findViewById(R.id.cbBtnCh4);
        cb5 = findViewById(R.id.cbBtnCh5);
        cb6 = findViewById(R.id.cbBtnCh6);
        cb7 = findViewById(R.id.cbBtnCh7);
        cb8 = findViewById(R.id.cbBtnCh8);
        cbxChannels = new CheckBox[]{cb1,cb2,cb3,cb4,cb5,cb5,cb7,cb8};

        rb1 = findViewById(R.id.rbBtnCh1);
        rb2 = findViewById(R.id.rbBtnCh2);
        rb3 = findViewById(R.id.rbBtnCh3);
        rb4 = findViewById(R.id.rbBtnCh4);
        rb5 = findViewById(R.id.rbBtnCh5);
        rb6 = findViewById(R.id.rbBtnCh6);
        rbBtnCen = findViewById(R.id.rbBtnCen);
        rbBtnSub = findViewById(R.id.rbBtnSub);
        rbtnChannels = new RadioButton[]{rb1,rb2,rb3,rb4,rb5,rb6,rbBtnCen,rbBtnSub};

        rgpChannels = findViewById(R.id.rgp_channels);

        atd1 = findViewById(R.id.atd_1);
        atd2 = findViewById(R.id.atd_2);
        atd3 = findViewById(R.id.atd_3);
        atd4 = findViewById(R.id.atd_4);
        atd5 = findViewById(R.id.atd_5);
        atd6 = findViewById(R.id.atd_6);
        atd7 = findViewById(R.id.atd_7);
        atd8 = findViewById(R.id.atd_8);
        advanceTimeDelays = new AdvanceTimeDelay[]{atd1,atd2,atd3,atd4,atd5,atd6,atd7,atd8};

        eqc_1 = findViewById(R.id.eqc_1);
        eqc_2 = findViewById(R.id.eqc_2);
        eqc_3 = findViewById(R.id.eqc_3);
        eqc_4 = findViewById(R.id.eqc_4);
        eqc_5 = findViewById(R.id.eqc_5);
        eqc_6 = findViewById(R.id.eqc_6);
        eqc_7 = findViewById(R.id.eqc_7);
        eqc_8 = findViewById(R.id.eqc_8);
        mEqChannel = new AdvanceChannel[]{eqc_1,eqc_2,eqc_3,eqc_4,eqc_5,eqc_6,eqc_7,eqc_8};

        link1 = findViewById(R.id.link1);
        link2 = findViewById(R.id.link2);
        link3 = findViewById(R.id.link3);
        link4 = findViewById(R.id.link4);
        link5 = findViewById(R.id.link5);
        link6 = findViewById(R.id.link6);
        link7 = findViewById(R.id.link7);
        mLinks = new CheckBox[]{link1,link2,link3,link4,link4,link6,link8};

        mCbxMute = findViewById(R.id.cbx_mute);
        sbTotalVol = findViewById(R.id.seekBarTotal);
        txtTotalVol = findViewById(R.id.txt_db_value);
        mBtnPlus = findViewById(R.id.ibtn_total_plus);
        mBtnSub = findViewById(R.id.ibtn_total_sub);


        setTitle("DELAY/GAIN");
        ViewUtil.initChannelName(cbxChannels);
        ViewUtil.initChannelName(rbtnChannels);

        mBtnPlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int progress = sbTotalVol.getProgress()/TOTAL_SCALE;
                progress++;
                if (progress > Constants.MAX_VOL) {
                    progress = Constants.MAX_VOL;
                }
                sbTotalVol.setProgress(progress*TOTAL_SCALE);
            }
        });

        rbBtnSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int progress = sbTotalVol.getProgress()/TOTAL_SCALE;
                progress--;
                if (progress < 0) {
                    progress = 0;
                }
                sbTotalVol.setProgress(progress*TOTAL_SCALE);
            }
        });
    }

    @Override
    protected int getCurrentBottomBtnId() {
        return com.qztech.sdk.R.id.bottom_btn_delay;
    }


    private CompoundButton.OnCheckedChangeListener timeDelayChangedListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            int i = Integer.parseInt(buttonView.getTag().toString());
            advanceTimeDelays[i].setEnabled(isChecked);
            ADVANCE_SETTINGS.setLastChannel(i);
        }
    };

    private CompoundButton.OnCheckedChangeListener levelChannelListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            int i = Integer.parseInt(buttonView.getTag().toString());
            mEqChannel[i].setEnabled(isChecked);
            int linkedMinIndex = ADVANCE_SETTINGS.setChannelChecked(i, isChecked ? 1 : 0, true);
            if (linkedMinIndex != -1) {
                syncLinkedChannel(linkedMinIndex);
            }
        }
    };


    private void enabledTotalVol(boolean enabled) {
        mBtnSub.setEnabled(enabled);
        mBtnPlus.setEnabled(enabled);
        sbTotalVol.setEnabled(enabled);
        mBtnSub.setAlpha(enabled?1f:DIENABLED_ALPHA);
        mBtnPlus.setAlpha(enabled?1f:DIENABLED_ALPHA);
        sbTotalVol.setAlpha(enabled?1f:DIENABLED_ALPHA);
        txtTotalVol.setEnabled(enabled);
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            updateData();
        } catch (Exception ex) {
            YzDebug.d("onResume", ex);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        DataUtil.saveAdvanceSettingsToDb();
        updateOk = false;
    }

    @Override
    public void onRefreshFragment(int cmd) {
        switch (cmd) {
            case CMD_SELECTED:
                updateData();
                break;
        }
    }

    private void syncLinkedChannel(int index) {
        if (index == -1) return;
        List<LevelChannel> levelChannels = ADVANCE_SETTINGS.getChannel();
        LevelChannel linkedChannel = levelChannels.get(index);
        for (int i = 0; i < levelChannels.size(); i++) {
            LevelChannel levelChannel = levelChannels.get(i);
            if (levelChannel.getLinked() == 1 && i != index) {
                levelChannel.setDegree(linkedChannel.getDegree());
                levelChannel.setMute(linkedChannel.getMute());
                levelChannel.setVal(linkedChannel.getVal());
                BLog.e("mute", (levelChannel.getMute() == 1 )+"");
                mEqChannel[i].setValue(levelChannel.getVal(), levelChannel.getMute() == 1, levelChannel.getDegree(), levelChannel.isChecked());
            }
        }
    }

    boolean isUpdated = false, updateOk = false;
    private final int TOTAL_SCALE = 10;
    private void updateData() {

        updateOk = false;
        float[] delays = ADVANCE_SETTINGS.getDelay(); //默认取第一个
        isUpdated = true;
        for (int i = 0, len = Math.min(advanceTimeDelays.length, delays.length); i < len; i++) {
            advanceTimeDelays[i].setValue(delays[i]);
            advanceTimeDelays[i].setTag(i);
            advanceTimeDelays[i].setEnabled(false);
            advanceTimeDelays[i].setOnSeekBarCallbacks(mAdvanceTimeDelaySeekbarCallbacks);
            rbtnChannels[i].setOnCheckedChangeListener(timeDelayChangedListener);
            final int index = i;
            rbtnChannels[i].setOnLongClickListener(v->{
                ViewUtil.showChangeChannelNameDialog(getContext(), index, name ->
                        rbtnChannels[index].setText(name));
                return true;
            });
        }
        int checkChannelId = ADVANCE_SETTINGS.getLastChannel();
        rgpChannels.check(rbtnChannels[checkChannelId].getId());
        advanceTimeDelays[checkChannelId].setEnabled(true);
        List<LevelChannel> channels = ADVANCE_SETTINGS.getChannel();
        try {
            for (int i = 0; i < channels.size(); i++) {
                LevelChannel channel = channels.get(i);
                cbxChannels[i].setChecked(channel.isChecked());
                mEqChannel[i].setValue(channel.getVal(), channel.getMute() == 1, channel.getDegree(), channel.isChecked());

                cbxChannels[i].setOnCheckedChangeListener(levelChannelListener);
                final int chIndex = i;
                cbxChannels[i].setOnLongClickListener(v->{
                    ViewUtil.showChangeChannelNameDialog(getContext(), chIndex, name ->
                            cbxChannels[chIndex].setText(name));
                    return true;
                });
                mEqChannel[i].setTag(i);
                mEqChannel[i].setOnSeekBarCallbacks(mAdvanceChannelSeekbarCallbacks);
                mEqChannel[i].setEnabled(cbxChannels[i].isChecked());

                mLinks[i].setTag(i);
                mLinks[i].setChecked(channel.getLinked() == 1);
                mLinks[i].setOnCheckedChangeListener((buttonView, isChecked) -> {
                    int index = (int) buttonView.getTag();
                    channel.setLinked(isChecked ? 1 : 0);
                    //LINKED选中后，对应通道也跟着选中，且只能通过LINKED取消；LINKED取消后，通道跟着取消选中
                    if (cbxChannels[index].isChecked() && isChecked) {
                        int baseIndex = ADVANCE_SETTINGS.getBaseIndex();
                        if (baseIndex != -1) {
                            syncLinkedChannel(baseIndex);
                        }
                    }
                    else {
                        cbxChannels[index].setChecked(isChecked);
                    }
                    mEqChannel[index].setEnabled(isChecked);

                });
            }

        } catch (Exception ex) {
            YzDebug.d("updateData", ex);
        }


        //总音量
        sbTotalVol.setMax(Constants.MAX_VOL*TOTAL_SCALE);
        txtTotalVol.setText((-Constants.MAX_VOL + ADVANCE_SETTINGS.getTotalVol()) + "dB"); //
        sbTotalVol.setProgress(ADVANCE_SETTINGS.getTotalVol()*TOTAL_SCALE);
        mCbxMute.setChecked(ADVANCE_SETTINGS.getMute() == 1);

        sbTotalVol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                progress = progress/10;
                int db = progress -Constants.MAX_VOL;
                if (db == -Constants.MAX_VOL){
                    txtTotalVol.setText("Off");
                }else {
                    txtTotalVol.setText(db+"dB");
                }
                if (!updateOk) return;
                if (System.currentTimeMillis() - mLastChangedTs > Constants.SEEK_BAR_DELAY) {
                    mLastChangedTs = System.currentTimeMillis();
                    ADVANCE_SETTINGS.sendTotalVolCmd(progress, mCbxMute.isChecked());
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) { }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //  seekBar.setProgress(progress);
                //txtTotalVol.setText(String.valueOf(-DspSettings.MAX_VOL + seekBar.getProgress()) + "dB");// - 20
                //DspSettings.ADVANCE_SETTINGS.sendTotalVolCmd(seekBar.getProgress(), mCbxMute.isChecked());
                ADVANCE_SETTINGS.sendTotalVolCmd(seekBar.getProgress()/TOTAL_SCALE, mCbxMute.isChecked());
            }
        });
        mCbxMute.setOnCheckedChangeListener((buttonView, isChecked) -> {
            enabledTotalVol(!isChecked);
            if (!updateOk) return;
            ADVANCE_SETTINGS.sendTotalVolCmd(sbTotalVol.getProgress()/TOTAL_SCALE, isChecked);
        });

        isUpdated = false;
        mCbxMute.postDelayed(() -> updateOk = true, 200);

    }




  //  @OnClick({R.id.ibtn_total_plus, R.id.ibtn_total_sub})
   /* public void onTotalPlusAndSubButtonClick(View v) {
        int progress = sbTotalVol.getProgress()/TOTAL_SCALE;
        switch (v.getId()) {
            case R.id.ibtn_total_plus:
                progress++;
                if (progress > Constants.MAX_VOL) {
                    progress = Constants.MAX_VOL;
                }
                break;
            case R.id.ibtn_total_sub:
                progress--;
                if (progress < 0) {
                    progress = 0;
                }
                break;
        }
        sbTotalVol.setProgress(progress*TOTAL_SCALE);
    }*/

    private AdvanceTimeDelay.OnSeekBarCallbacks mAdvanceTimeDelaySeekbarCallbacks = new AdvanceTimeDelay.OnSeekBarCallbacks() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, int currentIndex, boolean fromUser, boolean sendCmd) {
            if (!updateOk) return;
            ADVANCE_SETTINGS.setDelayValue(currentIndex, progress / 100f);
            if (sendCmd) {
                ADVANCE_SETTINGS.sendTimeDelayCmd(currentIndex);
            }
        }

        @Override
        public void onProgressChangeOver(SeekBar seekBar, int progress, int currentIndex) {
            ADVANCE_SETTINGS.setDelayValue(currentIndex, progress / 100f);
            if (!updateOk) return;
            ADVANCE_SETTINGS.sendTimeDelayCmd(currentIndex);
        }

    };

    //Level
    private AdvanceChannel.OnSeekBarCallbacks mAdvanceChannelSeekbarCallbacks = new AdvanceChannel.OnSeekBarCallbacks() {

        private void syncLinkedChannelVolume(LevelChannel levelChannel, boolean sendCmd) {
            List<LevelChannel> levelChannels = ADVANCE_SETTINGS.getChannel();
            for (int i = 0; i < levelChannels.size(); i++) {
                LevelChannel channel = levelChannels.get(i);
                if (channel.getLinked() == 1 && channel != levelChannel) {
                    channel.setVal(levelChannel.getVal());
                    mEqChannel[i].setValue(levelChannel.getVal(), false);
                    if (sendCmd) {
                        channel.sendVolume();
                    }
                }
            }
        }

        private void syncLinkedChannelMute(LevelChannel levelChannel, boolean sendCmd) {
            List<LevelChannel> levelChannels = ADVANCE_SETTINGS.getChannel();
            for (int i = 0; i < levelChannels.size(); i++) {
                LevelChannel channel = levelChannels.get(i);
                if (channel.getLinked() == 1 && channel != levelChannel) {
                    channel.setMute(levelChannel.getMute());
                    mEqChannel[i].setMute(channel.getMute() == 1, false);
                    if (sendCmd) {
                        channel.sendVolume();
                    }
                }
            }
        }

        private void syncLinkedChannelDegree(LevelChannel levelChannel, boolean sendCmd) {
            List<LevelChannel> levelChannels = ADVANCE_SETTINGS.getChannel();
            for (int i = 0; i < levelChannels.size(); i++) {
                LevelChannel channel = levelChannels.get(i);
                if (channel.getLinked() == 1 && channel != levelChannel) {
                    channel.setDegree(levelChannel.getDegree());
                    mEqChannel[i].setDegree(levelChannel.getDegree(), false);
                    if (sendCmd) {
                        channel.sendDegree();
                    }
                }
            }
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, int currentIndex, boolean fromUser, boolean sendCmd) {
            if (!updateOk) return;

            LevelChannel channel = ADVANCE_SETTINGS.getChannel().get(currentIndex);
            channel.setVal(progress);
            if (channel.getLinked() == 1) {
                syncLinkedChannelVolume(channel, sendCmd);
            }
            if (sendCmd) {
                channel.sendVolume();
            }
        }

        @Override
        public void onProgressChangeOver(SeekBar seekBar, int progress, int currentIndex) {
            if (!updateOk) return;
            LevelChannel channel = ADVANCE_SETTINGS.getChannel().get(currentIndex);
            channel.setVal(progress);
            if (channel.getLinked() == 1) {
                syncLinkedChannelVolume(channel, true);
            }
            channel.sendVolume();
        }

        @Override
        public void onMuteChanged(CompoundButton checkBox, boolean isChecked, int currentIndex) {
            if (!updateOk) return;
            LevelChannel channel = ADVANCE_SETTINGS.getChannel().get(currentIndex);
            channel.setMute(isChecked ? 1 : 0);
            channel.sendVolume();
            if (channel.getLinked() == 1) {
                syncLinkedChannelMute(channel, true);
            }
        }

        @Override
        public void onDegreeChanged(CompoundButton checkBox, boolean isChecked, int currentIndex) {
            if (!updateOk) return;
            LevelChannel channel = ADVANCE_SETTINGS.getChannel().get(currentIndex);
            channel.setDegree(isChecked ? 1 : 0);
            channel.sendDegree();
            if (channel.getLinked() == 1) {
                syncLinkedChannelDegree(channel, true);
            }
        }
    };

}
